package com.yangxk.upload.starter;

import com.yangxk.upload.provider.UploadProvider;
import com.yangxk.upload.provider.disk.DiskUploadProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(UploadProperties.class)
@ConditionalOnWebApplication
public class UploadAutoConfiguration {

    private UploadProperties uploadProperties;

    public UploadAutoConfiguration(UploadProperties uploadProperties) {
        this.uploadProperties = uploadProperties;
    }

    @Bean
    @ConditionalOnProperty(prefix = "fileupload.disk", name = "enabled", matchIfMissing = true)
    public UploadProvider diskUploadProvider() {
        DiskUploadProvider diskUploadProvider = new DiskUploadProvider();
        diskUploadProvider.setDiskDir(uploadProperties.getDisk().getDir());
        diskUploadProvider.setResourceMappingPrefix(uploadProperties.getDisk().getResourceMappingPrefix());
        return diskUploadProvider;
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.resources", name = "add-mappings", matchIfMissing = true)
    public ResourceMapping resourceMapping() {
        ResourceMapping resourceMapping = new ResourceMapping();
        resourceMapping.setUploadProperties(uploadProperties);

        return resourceMapping;
    }
}
